﻿using System.Linq;
using Myotragus.Data;
using Myotragus.Data.Containers;
using Myotragus.Data.Emit;
using Myotragus.Data.Hbm;
using Myotragus.Data.Registration;
using Myotragus.Data.RepositoryExtensions;
using Myotragus.Store.Model.Tests.Domain;
using NUnit.Framework;

namespace Myotragus.Store.Model.Tests
{
  [TestFixture]
  public class AutoHbmFixture
  {
    [SetUp]
    public void SetUp()
    {
      FixtureHelper.InitializeServices();

      var auto = FixtureHelper.Container.Resolve<IAutoProperties>();
      var generator = FixtureHelper.Container.Resolve<IAutomaticHbmGenerator>();
      var enti = FixtureHelper.Container.Resolve<IEntitiesRegistrar>();

      var ifs = EntitiesInterfaces.FromAssemblyContaining<IObject>();
      var impls = ifs.GenerateAutomaticImplementation(FixtureHelper.Container);
      var hbms = ifs.GenerateAutomaticHbm(FixtureHelper.Container);

      ((ITypeRegistrar) enti).RegisterForAll(impls);

      var factory = FixtureHelper.CreateSqlLiteDbFactory(hbms);

      var holder = FixtureHelper.Container.Resolve<ISessionFactoryAdapter>();
      holder.SetFactory(factory);
    }

    [Test]
    public void ObjecRepositoryCrud()
    {
      var repo = FixtureHelper.Container.Resolve<IObjectRepository>();
      var obj = repo.New(new {Name = "Erich", Id=1});

      var list = repo.FindAll();
      Assert.AreEqual(0, list.Count());
      Assert.AreEqual(0, repo.CountAll());
     
      repo.Save(obj);
      
      list = repo.FindAll();
      Assert.AreEqual(1, list.Count());
      Assert.AreEqual(1, repo.CountAll());
      
      list = repo.FindLike(new { Name = "Er" });
      Assert.AreEqual(1, list.Count());
      Assert.AreEqual(1, repo.CountLike(new { Name = "Er" }));

      list = repo.FindLike(new { Name = "Ledesma" });
      Assert.AreEqual(0, list.Count());
      Assert.AreEqual(0, repo.CountLike(new { Name = "Ledesma" }));

      list = repo.FindMatching(new { Name = "Erich" });
      Assert.AreEqual(1, list.Count());
      Assert.AreEqual(1, repo.CountMatching(new { Name = "Erich" }));

      list = repo.FindMatching(new { Name = "Ledesma" });
      Assert.AreEqual(0, list.Count());
      Assert.AreEqual(0, repo.CountMatching(new { Name = "Ledesma" }));
      
      repo.Delete(obj);

      list = repo.FindAll();
      Assert.AreEqual(0, list.Count());
      Assert.AreEqual(0, repo.CountAll());
    }

    [Test]
    public void CategoryRepositoryCrud()
    {
      var repo = FixtureHelper.Container.Resolve<IRepository<ICategory>>();
    }
  }
}
